//
//  HEAddressMapViewController.m
//  HealthFamily
//
//  Created by 吴欧 on 2020/11/12.
//  Copyright © 2020 honglutec. All rights reserved.
//

#import "HEAddressMapViewController.h"

#import "HEMapAddressInfoCell.h"

@interface HEAddressMapViewController ()<QMUITextFieldDelegate, BMKMapViewDelegate,UITableViewDelegate,UITableViewDataSource,BMKGeoCodeSearchDelegate, BMKLocationManagerDelegate, BMKSuggestionSearchDelegate, BMKPoiSearchDelegate>

@property(nonatomic,weak) BMKMapView *mapView;//地图
@property(nonatomic,strong) BMKGeoCodeSearch *searcher;//编码

@property (nonatomic, strong) BMKLocationManager *locationManager; //定位对象
@property (nonatomic, strong) BMKUserLocation *userLocation; //当前位置对象

@property(nonatomic,weak) GDTableView *tableView;

@property(nonatomic,strong) NSMutableArray<HEReceiveAddressModel *> *dataList;//信息

@property (nonatomic, assign) NSIndexPath *selectIndex;//单选，当前选中的行
@property (nonatomic, strong) CLLocationManager *sysLocManager;

@property (nonatomic, assign) BOOL hasReqGeo;
@property (nonatomic, strong) QMUITextField *searchTF;

@property (nonatomic, assign) CLLocationCoordinate2D currentSelectLoc;
@property (nonatomic, strong) BMKLocation *courrentLoc;

@end

@implementation HEAddressMapViewController

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.mapView viewWillAppear];
    self.searcher.delegate = self;
    self.mapView.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.mapView viewWillDisappear];
    self.mapView.delegate = nil; // 不用时，置nil
    self.searcher.delegate = nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"选择地址";
 
    [self requestWhenInUseAuthorization];
    
    
    [self setupMapView];
    [self setupSerachUI];
     [self startlocation];
}


-(void)requestWhenInUseAuthorization {
    if (![self getUserLocationAuth]) {
         if ([self.sysLocManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
            [self.sysLocManager requestWhenInUseAuthorization];
        }
    }
}


- (BOOL)getUserLocationAuth {
    BOOL result = NO;
    switch ([CLLocationManager authorizationStatus]) {
        case kCLAuthorizationStatusNotDetermined: //用户没有选择是否要使用定位服务（弹框没选择，或者根本没有弹框）
            break;
        case kCLAuthorizationStatusRestricted: //定位服务授权状态受限制，可能由于活动限制了定位服务，并且用户不能改变当前的权限，这个状态有可能不是用户拒绝的，但是也有可能是用户拒绝的
            break;
        case kCLAuthorizationStatusDenied: //用户在设置中关闭定位功能，或者用户明确的在弹框之后选择禁止定位
            [Dialog toastBottom:@"请前往设置开启定位权限~"];
            break;
        case kCLAuthorizationStatusAuthorizedAlways:
            result = YES;
            break;
        case kCLAuthorizationStatusAuthorizedWhenInUse:
            result = YES;
            break;
            
        default:
            break;
    }
    return result;
}

- (CLLocationManager *)sysLocManager {
    if (!_sysLocManager) {
        _sysLocManager = [[CLLocationManager alloc] init];
        _sysLocManager.desiredAccuracy = kCLLocationAccuracyBest;
        _sysLocManager.distanceFilter = kCLLocationAccuracyHundredMeters;
    }
    return _sysLocManager;
}

- (void)setupSerachUI {
    
    UIView *serchWarp = [UIView new];
    [self.view addSubview:serchWarp];
    
    serchWarp.qmui_borderPosition = QMUIViewBorderPositionBottom | QMUIViewBorderPositionTop;
    serchWarp.qmui_borderWidth = 1;
    serchWarp.qmui_borderColor = CSplitLineColor;
    
    [serchWarp mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_mapView.mas_bottom);
        make.left.right.equalTo(self.view);
        make.height.mas_offset(60);
    }];
    
    // 输入框
    QMUITextField *searchTF = [[QMUITextField alloc] init];
    searchTF.backgroundColor = KHexColor(@"F1F3F8");
    searchTF.layer.cornerRadius = 20;
    searchTF.font = DYFont(16);
    searchTF.placeholder = @"搜索地点";
    searchTF.placeholderColor = [UIColor colorWithHexString:@"#AAAAAA"];
    searchTF.delegate = self;
    _searchTF = searchTF;
    [serchWarp addSubview:searchTF];
    
    UIView *leftWarp = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 49, 18)];
    UIImageView *leftIcon = [[UIImageView alloc] initWithImage:IMAGE_NAMED(@"search")];
    leftIcon.frame = CGRectMake(20, 0, 18, 18);
    [leftWarp addSubview:leftIcon];
    searchTF.leftViewMode = UITextFieldViewModeAlways;
    searchTF.leftView = leftWarp;
    
    // 搜索按钮
//    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
//    [btn setTitle:@"取消" forState:UIControlStateNormal];
//    btn.titleLabel.font = DYFont(16);
//    [btn setTitleColor:CNavSubTitleColor forState:UIControlStateNormal];
//    [serchWarp addSubview:btn];
    
    [searchTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(serchWarp).mas_offset(10);
        make.left.equalTo(serchWarp.mas_left).mas_offset(10);
        make.right.equalTo(serchWarp.mas_right).mas_offset(-10);
        make.bottom.equalTo(serchWarp).mas_offset(-10);
    }];
    
//    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(serchWarp);
//        make.right.equalTo(serchWarp.mas_right);
//        make.bottom.equalTo(serchWarp);
//        make.width.mas_offset(80);
//    }];
//
    
    GDTableView *tableView = [[GDTableView alloc]initWithFrame:CGRectMake(0, kScreenHeight * 0.4 + 60, KScreenWidth, kScreenHeight  - kScreenHeight * 0.4 - 60) style:UITableViewStylePlain];
    self.tableView = tableView;
    _tableView.separatorColor = CSplitLineColor;
    _tableView.scrollsToTop = YES;
    _tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 0.01)];
    _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 0.01)];
    tableView.delegate = self;
    tableView.dataSource = self;
    
 
    
    [tableView registerClass:[HEMapAddressInfoCell class] forCellReuseIdentifier: @"HEMapAddressInfoCell"];
    [self.view addSubview:tableView];
}

- (void)setupMapView{
    BMKMapView *mapView = [[BMKMapView alloc]init];
    [self.view addSubview:mapView];
    [mapView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.view);
        make.height.offset(kScreenHeight * 0.4);
    }];
    self.mapView = mapView;
    //设置mapView的代理
    _mapView.delegate = self;
    
    
    UIButton *button = [[UIButton alloc]init];
    [button setImage:[UIImage imageNamed:@"gpers_icon"] forState:UIControlStateNormal];
    [mapView addSubview:button];
    [button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(mapView);
    }];
    
    self.mapView.showsUserLocation = YES;//显示定位图层
    self.mapView.userTrackingMode = BMKUserTrackingModeFollow;//设置定位的状态
    self.mapView.zoomLevel = 16;//地图显示的级别
}

- (void)startlocation {
    //开启定位服务
    [self.locationManager startUpdatingLocation];
}


#pragma mark - UITableViewDelegate && dataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    HEMapAddressInfoCell *cell = [tableView dequeueReusableCellWithIdentifier: @"HEMapAddressInfoCell"];
    cell.model = self.dataList[indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [tableView fd_heightForCellWithIdentifier: NSStringFromClass(HEMapAddressInfoCell.class) cacheByIndexPath:indexPath configuration:^(HEMapAddressInfoCell *cell) {
        cell.model = self.dataList[indexPath.row];
     }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
 
    [self resetSelect];
    HEReceiveAddressModel *model = self.dataList[indexPath.row];
    model.isSelect = YES;
    [self.tableView reloadData];

    [self.navigationController popViewControllerAnimated:YES];
    if (self.selectAddressBlock) {
        self.selectAddressBlock(model);
    }
}

- (void)resetSelect {
    for (HEReceiveAddressModel *model in self.dataList) {
        model.isSelect = NO;
    }
}

// 反geo检索 随后调用delegate
- (void)reverseGeoCodeSearch:(CLLocationCoordinate2D)centerCoordinate {
    // 反geo检索 随后调用delegate
    BMKReverseGeoCodeSearchOption *reverseGeocodeSearchOption = [[BMKReverseGeoCodeSearchOption alloc]init];
    reverseGeocodeSearchOption.location = centerCoordinate;
    BOOL flag = [self.searcher reverseGeoCode:reverseGeocodeSearchOption];
    if(flag) {
        _hasReqGeo = YES;
        NSLog(@"反geo检索发送成功");
    } else {
        NSLog(@"反geo检索发送失败");
    }
}

#pragma mark - baidu map
#pragma mark - BMKMapViewDelegate
 
- (void)mapView:(BMKMapView *)mapView regionDidChangeAnimated:(BOOL)animated{
    BMKCoordinateRegion region;
    CLLocationCoordinate2D centerCoordinate = mapView.region.center;
    region.center = centerCoordinate;
    _currentSelectLoc = centerCoordinate;
    [self reverseGeoCodeSearch:centerCoordinate];
}

#pragma mark - BMKGeoCodeSearchDelegate
//接收反向地理编码结果
- (void) onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeSearchResult *)result errorCode:(BMKSearchErrorCode)error {
    if (error == BMK_SEARCH_NO_ERROR) {
        //在此处理正常结果
        
        [self.dataList removeAllObjects];
        for (BMKPoiInfo *point in result.poiList) {
            HEReceiveAddressModel *addModel = [HEReceiveAddressModel new];
            addModel.province = result.addressDetail.province;
            addModel.city = result.addressDetail.city;
            addModel.region = result.addressDetail.district;
            addModel.latitude = point.pt.latitude;
            addModel.longitude = point.pt.longitude;
            addModel.detailAddress = point.address;
            addModel.addressTitle = point.name;
 
            BMKMapPoint point1 = BMKMapPointForCoordinate(_userLocation.location.coordinate);
            BMKMapPoint point2 = BMKMapPointForCoordinate(point.pt);

            CLLocationDistance distance = BMKMetersBetweenMapPoints(point1, point2);
 
            addModel.distance = [DYTools distanceWithStringMTransformKm:distance];
            [self.dataList  addObject:addModel];
        }
        [self.tableView reloadData];

    } else {
        NSLog(@"抱歉，未找到结果");
    }
}

#pragma mark - TextFiledDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

    NSString *text = [textField.text stringByReplacingCharactersInRange:range withString:string];
    [self setupDefaultData: text];
    return YES;
}

#pragma mark - Search Data
- (void)setupDefaultData:(NSString *)keyword {

    //初始化请求参数类BMKSuggestionSearchOption的实例
    BMKSuggestionSearchOption *suggestionOption = [[BMKSuggestionSearchOption alloc] init];
    //检索关键字
    suggestionOption.keyword = keyword;
    //城市名
    suggestionOption.cityname = _courrentLoc.rgcData.city;
    //是否只返回指定城市检索结果（默认：NO）（提示：海外区域暂不支持设置cityLimit）
    suggestionOption.cityLimit = NO;
    [self searchData:suggestionOption];
}

- (void)searchData:(BMKSuggestionSearchOption *)option {
    
    //初始化BMKPoiSearch实例
    BMKPoiSearch *POISearch = [[BMKPoiSearch alloc] init];
    //设置POI检索的代理
    POISearch.delegate = self;
    
    //初始化BMKSuggestionSearch实例
    BMKSuggestionSearch *suggestionSearch = [[BMKSuggestionSearch alloc] init];
    //设置关键词检索的代理
    suggestionSearch.delegate = self;
    //初始化请求参数类BMKSuggestionSearchOption的实例
    BMKSuggestionSearchOption* suggestionOption = [[BMKSuggestionSearchOption alloc] init];
    //城市名
    suggestionOption.cityname = option.cityname;
    //检索关键字
    suggestionOption.keyword  = option.keyword;
    //是否只返回指定城市检索结果，默认为NO（海外区域暂不支持设置cityLimit）
    suggestionOption.cityLimit = option.cityLimit;
    /**
     关键词检索，异步方法，返回结果在BMKSuggestionSearchDelegate
     的onGetSuggestionResult里
     
     suggestionOption sug检索信息类
     成功返回YES，否则返回NO
     */
    BOOL flag = [suggestionSearch suggestionSearch:suggestionOption];
    if(flag) {
        NSLog(@"关键词检索成功");
    } else {
        NSLog(@"关键词检索失败");
    }
}

#pragma mark - BMKPoiSearchDelegate
#pragma mark - BMKSuggestionSearchDelegate
/**
 关键字检索结果回调
 
 @param searcher 检索对象
 @param result 关键字检索结果
 @param error 错误码，@see BMKCloudErrorCode
 */
- (void)onGetSuggestionResult:(BMKSuggestionSearch *)searcher result:(BMKSuggestionSearchResult *)result errorCode:(BMKSearchErrorCode)error {
    //BMKSearchErrorCode错误码，BMK_SEARCH_NO_ERROR：检索结果正常返回
    if (error == BMK_SEARCH_NO_ERROR) {
        
        [self.dataList removeAllObjects];
        for (BMKSuggestionInfo *point in result.suggestionList) {
            HEReceiveAddressModel *addModel = [HEReceiveAddressModel new];
            addModel.province = _courrentLoc.rgcData.province;
            addModel.city = point.city;
            addModel.region = point.district;
            addModel.latitude = point.location.latitude;
            addModel.longitude = point.location.longitude;
            addModel.detailAddress = point.address;
            addModel.addressTitle = point.key;

            BMKMapPoint point1 = BMKMapPointForCoordinate(_userLocation.location.coordinate);
            BMKMapPoint point2 = BMKMapPointForCoordinate(point.location);
            CLLocationDistance distance = BMKMetersBetweenMapPoints(point1, point2);
            addModel.distance = [DYTools distanceWithStringMTransformKm:distance];
            [self.dataList  addObject:addModel];
        }
        [self.tableView reloadData];
    }
}


#pragma mark - 定位 BMKLocationManagerDelegate
/**
 @brief 当定位发生错误时，会调用代理的此方法
 @param manager 定位 BMKLocationManager 类
 @param error 返回的错误，参考 CLError
 */
- (void)BMKLocationManager:(BMKLocationManager * _Nonnull)manager didFailWithError:(NSError * _Nullable)error {
    NSLog(@"定位失败");
}

/**
 @brief 该方法为BMKLocationManager提供设备朝向的回调方法
 @param manager 提供该定位结果的BMKLocationManager类的实例
 @param heading 设备的朝向结果
 */
- (void)BMKLocationManager:(BMKLocationManager *)manager didUpdateHeading:(CLHeading *)heading {
    if (!heading) {
        return;
    }
    NSLog(@"用户方向更新");
    
    self.userLocation.heading = heading;
    [_mapView updateLocationData:self.userLocation];
}

/**
 @brief 连续定位回调函数
 @param manager 定位 BMKLocationManager 类
 @param location 定位结果，参考BMKLocation
 @param error 错误信息。
 */
- (void)BMKLocationManager:(BMKLocationManager *)manager didUpdateLocation:(BMKLocation *)location orError:(NSError *)error {
    if (error) {
        NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
    }
    if (!location) {
        return;
    }
    
    self.userLocation.location = location.location;
    //实现该方法，否则定位图标不出现
    [_mapView updateLocationData:self.userLocation];
    _courrentLoc = location;

    if (!_hasReqGeo) {
        _currentSelectLoc = _userLocation.location.coordinate;
        [self reverseGeoCodeSearch: location.location.coordinate];
    }
}


#pragma mark - lazyLoad

- (BMKLocationManager *)locationManager {
    if (!_locationManager) {
        //初始化BMKLocationManager类的实例
        _locationManager = [[BMKLocationManager alloc] init];
        //设置定位管理类实例的代理
        _locationManager.delegate = self;
        //设定定位坐标系类型，默认为 BMKLocationCoordinateTypeGCJ02
        _locationManager.coordinateType = BMKLocationCoordinateTypeBMK09LL;
        //设定定位精度，默认为 kCLLocationAccuracyBest
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        //设定定位类型，默认为 CLActivityTypeAutomotiveNavigation
        _locationManager.activityType = CLActivityTypeAutomotiveNavigation;
        //指定定位是否会被系统自动暂停，默认为NO
        _locationManager.pausesLocationUpdatesAutomatically = NO;
        /**
         是否允许后台定位，默认为NO。只在iOS 9.0及之后起作用。
         设置为YES的时候必须保证 Background Modes 中的 Location updates 处于选中状态，否则会抛出异常。
         由于iOS系统限制，需要在定位未开始之前或定位停止之后，修改该属性的值才会有效果。
         */
        _locationManager.allowsBackgroundLocationUpdates = NO;
        /**
         指定单次定位超时时间,默认为10s，最小值是2s。注意单次定位请求前设置。
         注意: 单次定位超时时间从确定了定位权限(非kCLAuthorizationStatusNotDetermined状态)
         后开始计算。
         */
        _locationManager.locationTimeout = 10;
    }
    return _locationManager;
}

- (BMKUserLocation *)userLocation {
    if (!_userLocation) {
        //初始化BMKUserLocation类的实例
        _userLocation = [[BMKUserLocation alloc] init];
    }
    return _userLocation;
}

- (BMKGeoCodeSearch *)searcher{
    if (!_searcher) {
        _searcher =[[BMKGeoCodeSearch alloc]init];
    }
    return _searcher;
}

- (NSMutableArray *)dataList {
    if (!_dataList) {
        _dataList = [NSMutableArray array];
    }
    return _dataList;
}

- (void)selectAddress:(SelectAddress)block {
    self.selectAddressBlock = block;
}

@end
